import json
import os
from datetime import datetime

import pytest
from utils.email_util import Email_Utils
from utils.log_util import setup_logger
from config.constants import *
from utils.zipfile_util import zip_allure_report
from utils.shutil_util import *
from utils.wxworksms import WxWorkSms
from utils.allure_json import parse_allure_json
import sys
import os

# 获取项目根目录（假设 run.py 在项目根目录下）
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)  # 添加到 Python 路径
def calculate_pass_rate(passed, total):
    """计算通过率"""
    #防止除零错误：如果 total = 0，直接计算会报错，这个函数会安全返回 0
    return (passed / total * 100) if total > 0 else 0


if __name__ == '__main__':
    # 初始化
    logg, log_file = setup_logger()
    wx = WxWorkSms('3ff6fcd5-5525-4a33-90e8-07589e188fa6')

    # 清理旧数据
    clear_allure_results_dirs(['./temp/report', './zipfile/allure.zip'])

    # 执行测试
    pytest.main([
        '--env=dev',
        '-vs',
        '--alluredir=./temp/report',
        '--reruns=3',  # 新增：失败重跑 3 次
        '--reruns-delay=1',
        # 新增：每次重跑间隔 1 秒
        '-m','wms_all'
    ])
    # 生成报告
    os.system('allure generate ./temp/report -o ./report/result --clean')

    # 压缩报告
    zip_allure_report('./temp', os.path.join(ZIPFILE_PATH, 'allure.zip'))

    # 解析测试结果
    report_dir = os.path.join(TEMP_PATH, "temp", "report")
    results = parse_allure_json(TEMP_PATH)
    print(f"总用例数:{results['total']}")
    print(f"通过数: {results['passed']}")
    print(f"失败数: {results['failed']}")

    # 准备当前运行数据
    current_results = {
        "project_name": "WMS系统",
        "project_port": "8080",
        "total": results['total'],
        "passed": results.get('passed'),
        "failed": results.get('failed'),
        "skipped": results.get('skipped'),
        "broken": results.get('broken'),
        "pass_rate": calculate_pass_rate(results.get('passed'), results.get('total')),
        "run_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }

    # 读取历史数据
    history_results = None
    if os.path.exists('history.json'):
        try:
            with open('history.json', 'r', encoding='utf-8') as f:
                history_data = json.load(f)
                # 确保关键字段存在，否则设为默认值
                history_results = {
                    "total": history_data.get("total", 0),
                    "passed": history_data.get("passed", 0),
                    "failed": history_data.get("failed", 0),
                    "skipped": history_data.get("skipped", 0),
                    "broken": history_data.get("broken", 0),
                    "run_time": history_data.get("run_time", "未知时间"),
                }
                # 计算历史数据的通过率
                history_results["pass_rate"] = calculate_pass_rate(
                    history_results["passed"],
                    history_results["total"]
                )
        except (json.JSONDecodeError, FileNotFoundError):
            history_results = None

    # 发送消息
    wx.send_markdown_with_history(current_results, history_results)

    # 保存当前结果为历史记录
    try:
        with open('history.json', 'w') as f:
            json.dump(current_results, f)
    except IOError as e:
        print(f"保存历史记录失败: {e}")

    # 发送报告和附件
    report_path = os.path.join(REPORT_PATH, 'result')
    wx.send_report(report_path)

    excel_path = os.path.join(DATA_PATH, '测试用例.xlsx')
    if os.path.exists(excel_path):
        wx.send_file(excel_path)